<template>
  <div class="pdi-container">
    <FormPanel :list="topFilterList" :cols="3" :labelWidth="100" :collapse="false" :isSubmitBtn="false" />
    <!-- <FilterTable
      ref="mainTable"
      :columns="tableColumns"
      columnsRef="partInventoryInfo"
      :datakey="'rows'"
      selectionType="single"
      :dataSource="dataSource"
      :onColumnsChange="columns => (this.tableColumns = columns)"
    >
    </FilterTable> -->
            <!--        附件页面 -->
        <BaseDialog
            id="multiEnter"
            :visible.sync="attachmentVisible"
            title="附件"
            destroyOnClose
            :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px', width: '90%', margin: 'auto' }"
        >
          <!-- <UploadFile
              v-if="isButtonShow"
              ref="UploadFile"
              :autoUpload="true"
              :autoUploadDisplay="false"
              :action-url="'/api/dms.download/file/upload'"
              :file-list="fileList"
              :limit="5"
              @change="successHandler"
              :fileTypes="['jpg', 'png']"
          >新增附件
          </UploadFile> -->
          <el-table :data="dataList" border>
            <el-table-column type="index" label="ID" width="60" align="center"></el-table-column>
            <el-table-column prop="fileName" label="附件名称">
              <template v-slot="{ row }">
                <el-button @click="getBarcode(row.fileUrl)" type="text" size="small">{{ row.fileName }}</el-button>
              </template>
            </el-table-column>

            <el-table-column prop="createdAt" label="上传时间"></el-table-column>
            <el-table-column v-if="false" prop="pdiAnsFileId" label="附件id"></el-table-column>
            <el-table-column v-if="isButtonShow" prop="vsPdiAnswerDetailFileDTOList" label="操作">
              <template slot-scope="scope">
                <el-button @click="deleteRow(scope)" type="text" size="small">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="text-align: center; margin-top: 30px">
            <!-- <el-button v-if="isButtonShow" size="small" type="primary" @click="saveAttachment">保存</el-button> -->
            <el-button size="small" type="primary" @click="cancelEnter">取消</el-button>
          </div>
        </BaseDialog>

          <!--    合并单元格的表格-->
      <div>
        <!-- <FormPanel ref="formListBaseInfo" :list="formListBaseInfo" :is-submit-btn="false" :cols="3"/> -->
        <div class="form-panel">
          <el-table v-loading="tableLoading" :data="templateTableData" :span-method="objectSpanMethod" border>
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <el-table-column prop="firstQuestion" label="类别"></el-table-column>
            <el-table-column v-if="false" prop="pdiAnsDetailId" label="明细id"></el-table-column>
            <el-table-column v-if="isShowColumn('secondQuestion')" prop="secondQuestion" label="项目"></el-table-column>
            <el-table-column v-if="isShowColumn('thirdQuestion')" prop="thirdQuestion" label="内容"></el-table-column>
            <el-table-column prop="pdiChoose" label="是否有问题" align="center">
              <template v-slot="{ row }">
                <el-radio-group :disabled="pdiChooseDisabled" v-model="row.pdiChoose">
                  <el-radio :label="10041001"><span style="color:black;">是</span></el-radio>
                  <el-radio :label="10041002"><span style="color:black;">否</span></el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="vsPdiAnswerDetailFileDTOList" label="附件" align="center">
              <template v-slot="{ row }">
                <div v-if="row.vsPdiAnswerDetailFileList != null">
                <el-button  size="mini" type="primary" @click="showHandle(row)">查看
                </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="pdiDesc" label="问题描述" align="center">
              <template v-slot="{ row }">
                <el-input :disabled="pdiChooseDisabled" v-model="row.pdiDesc"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <BaseDialog
            id="multiEnter1"
            :visible.sync="imageVisible"
            title="图片预览"
            destroyOnClose
            :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px', width: '90%', margin: 'auto' }"
        >
          <el-image :src="barcodeUrl" placeholder="Barcode"></el-image>

        </BaseDialog>
    <div class="pdi-foot">
      <el-button size="small" type="primary" @click="cancel">返回</el-button>
    </div>
  </div>
  </div>
</template>
<script>
// import { partbuyStockInItemOEM } from '@/api/part/partInventory/partInventory/index.js';
import { dictionary } from '@/utils/dictMixin';
import { queryPDIDetailById,downLoadAttachImage } from '@/api/repair/PDIMessageForFactory/index';
// import { byAllInfo } from '@/api/part/allocation';
import { getStorageList, querySysParam } from '@/api/part/common';

export default {
  name: 'partBuyItems',
  props: {
    top: {}
  },
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      // tableColumns: this.createTableColumns(),
      formListBaseInfo: this.createFormColumns(),
      barcodeUrl: '',
      imageVisible: false,
      deleteObject: {}, //要合并的单元格对象，需要隐掉
      pdiChooseDisabled: false,
      attachmentVisible: false,
      dataList: [],
      maptype: {},
      templateTableData: [],
      fetchParams: {},
      dataSource: [],
      tableLoading: false,
      isButtonShow: true,//控制所有按钮的是否显示
      storageDic: [
        { text: 'OEM电', value: 'OEM-ELECTIC' },
        { text: 'OEM油', value: 'OEM-OIL' }
      ] // 仓库字典
    };
  },
  mounted() {
    this.initTemplate();
    //this.queryDetailById(this.top);
    // this.getStorage();
    this.findBuyItems();
    
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: 'PDI类型',
          fieldName: 'pdiTypeName',
          initialValue: '',
          width: 120,
          disabled: true
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          initialValue: '',
          width: 120,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车型',
          width: 120,
          fieldName: 'modelName',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '服务中心代码',
          initialValue: '',
          width: 120,
          fieldName: 'dealerCode',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '服务中心简称',
          initialValue: 0,
          width: 120,
          fieldName: 'dealerName',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '检查人',
          initialValue: '',
          width: 120,
          fieldName: 'createdBy',
          //itemList: this.createDictList(8088),
          disabled: true
        },
        {
          type: 'DATE',
          fieldName: 'pdiEntryDate',
          initialValue: '',
          width: 120,
          label: '检查时间',
          dateFormat: 'yyyy-MM-dd',
          disabled: true
        }
      ];
    },
    createFormColumns() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '检查明细'
        },
        {
          type: 'SELECT',
          label: '批量录入检查结果',
          fieldName: 'auditType',
          itemList: this.createDictList(1004),
          change: val => {
            this.changeTableList(val)
          }
        }
      ]
    },
    initTemplate() {
        this.getCheckModel()
      // this.topFilterList.find(x => {
      //   if (x.fieldName === 'vin') {
      //     x.initialValue = this.top.vin ? this.top.vin : ''
      //   }
      //   if (x.fieldName === 'pdiEntryPerson') {
      //     x.initialValue = window.sessionStorage.getItem('employeeName')
      //   }
      // })
      //PDI检查单查询页面进入要关掉所有修改权限
      this.initDisabled()
    },
        initDisabled() {
        this.pdiChooseDisabled = true
        this.isButtonShow = false
        this.topFilterList.forEach(x => {
          x.disabled = true
        })
        // this.formListBaseInfo.find(x => x.fieldName === 'auditType').hidden = true
      
    },
        //只支持合并单元行，不支持合并列
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.maptype[column.property]) {
        if (this.maptype[column.property][rowIndex]) {
          //endSpanIndex=起始合并行+合并行总数
          //组装要合并掉需要隐藏的单元格数组对象
          this.deleteObject[column.property] = {
            startSpanIndex: rowIndex,
            endSpanIndex: rowIndex + this.maptype[column.property][rowIndex]
          }
          //合并操作
          return {
            rowspan: this.maptype[column.property][rowIndex],
            colspan: 1
          }
        } else if (this.deleteObject[column.property] && rowIndex > this.deleteObject[column.property].startSpanIndex && rowIndex < this.deleteObject[column.property].endSpanIndex) {
          //隐藏被合并的对象
          // return {
          //   rowspan: 0,
          //   colspan: 0
          // }
        } else {
          //正常显示
          return {
            rowspan: 1,
            colspan: 1
          }
        }
      }
    },
    cancelEnter() {
      this.attachmentVisible = false
    },
    isShowColumn(columnName) {
      const res =
          this.templateTableData.filter(rowData => {
            const flag = rowData[columnName] !== undefined && rowData[columnName] !== '' && rowData[columnName] !== null
            return flag
          }).length > 0

      console.log(columnName, 'res', res)
      return res
    },
    showHandle(row) {
      if (!row.vsPdiAnswerDetailFileList) {
        this.$set(row, 'vsPdiAnswerDetailFileList', [])
      }
      this.dataList = row.vsPdiAnswerDetailFileList
      this.attachmentVisible = true
    },
    getBarcode(url) {
      downLoadAttachImage(url).then(res => {
        this.barcodeUrl = URL.createObjectURL(res.data)
        this.imageVisible = true
        console.log('res=', res)
      })
    },
    //获取页面表格模版数据
    getCheckModel() {
      //this.tableLoading = true
      // let param = {
      //   vin: this.top.vin,
      //   poNo: this.top.poNo,
      //   pdiType: this.top.pdiType,
      //   shipmentNo: this.top.shipmentNo
      // }
      queryPDIDetailById({pdNo:this.top.pdNo,ownerCode:this.top.ownerCode})
          .then(res => {
            //获取文件模版失败，关掉保存按钮和确认检查按钮
            if (!res.data) {
              this.isButtonShow = false
            }
            const { resultCode } = res
            if (resultCode === 200) {
              this.templateTableData = res.data.vsPdiAnswerDetailCheckList
              //是否有问题列不需要默认值
              this.templateTableData.forEach(x => {
                // if (x.pdiChoose) {
                //   x.pdiChoose = ''
                // }
              })
              this.changeRowSpan()
              console.log('this.templateTableData==', this.templateTableData)
            } else {
              this.$message.error('获取模版文件失败！请稍后再试')
            }
          })
          .finally(() => {
            this.tableLoading = false
          })
    },
    //发送请求获取检查项目附件等数据  通过PDI单号
    // async queryDetailById(top) {
    //   console.log(JSON.stringify(this.top.pdiType)+"------------------------------this.top")
    //   // let name = '';
    //   // let res = await queryPDIDetailById({ pdNo: top.pdNo,ownerCode: top.ownerCode});
    //   // if (res.resultCode == 200 && res.data && res.data.records && res.data.records.length > 0) {
    //   //   name = res.data.records[0].companyName;
    //   // }
    //   this.topFilterList.find(x => x.fieldName == 'ownerName').initialValue = name;
    // },
        //获取/定位到需要合并单元格的index
    changeRowSpan() {
      const _this = this
      let keys = Object.keys(this.templateTableData[1])
      keys.forEach(columnName => {
        if(columnName !== 'firstQuestion'|| columnName !== 'secondQuestion' 
         || columnName !== 'thirdQuestion' || columnName === undefined || columnName === null){
          return;
        }
        if (columnName == 'firstQuestion' || columnName == 'secondQuestion' || columnName == 'thirdQuestion') {
          console.log(columnName)
          for (let i = 0; i < this.templateTableData.length;) {
            let span = i + 2
            let j = i + 1
            for (; j < span; j++) {
              if (span < _this.templateTableData.length + 1 && _this.templateTableData[i][columnName] === _this.templateTableData[j][columnName]) {
                if (!_this.maptype[columnName]) {
                  _this.maptype[columnName] = {}
                }
                if (!_this.maptype[columnName][i + '']) {
                  _this.maptype[columnName][i + ''] = 1
                }
                _this.maptype[columnName][i + ''] += 1
                span++
              }
            }
            i = j - 1
          }
        }
      })

      this.maptype = _this.maptype
    },
    async getStorage() {
      const ckRes = await getStorageList();
      const ckDict = ckRes.data.map(x => ({ text: x['STORAGE_NAME'], value: x['STORAGE_CODE'] }));
      this.storageDic = ckDict;
      this.tableColumns.find(x => x.dataIndex == 'STORAGE_CODE').filterItems = this.tableColumns.find(x => x.dataIndex == 'STORAGE_CODE').dictItems = ckDict;
    },
    async findBuyItems() {
      this.topFilterList.map(x => {
        x.initialValue = this.top[x.fieldName];
      });
      // let res = await partbuyStockInItemOEM({ stockInNo: this.top.stockInNo, ownerCode: this.top.ownerCode });
      // this.dataSource = res.data;
    },
    cancel() {
      this.$emit('close')
    },
  }
};
</script>
<style scoped lang="less">
.pdi-container {
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;

  .pid-content {
    flex: 1;
    overflow-y: auto;
  }

  .pdi-foot {
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 1px solid #d9d9d9;
  }
}
.pdi-container {
  /deep/ .el-table {
    border: 1px solid #d9d9d9 !important;
    margin-bottom: 10px;
  }

  /deep/ .el-table--border th {
    border-right: 1px solid #d9d9d9 !important;
  }

  /deep/ .el-table--border tr {
    border-right: 1px solid #d9d9d9 !important;
  }

  /deep/ .el-table--border td {
    border-right: 1px solid #d9d9d9 !important;
  }

  /deep/ .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #ffffff !important;
  }
}
</style>